package com.legrand.www.module.authentication.controller;

import com.legrand.www.module.authentication.dto.TokenDTO;
import com.legrand.www.module.authentication.pto.UserPTO;
import com.legrand.www.module.core.entity.User;
import com.legrand.www.module.security.util.UserUtil;
import com.legrand.www.module.core.response.BaseResponse;
import com.legrand.www.module.core.util.JwtToken;
import com.legrand.www.module.core.util.TokenUtil;
import com.legrand.www.module.common.util.PhoneAndIDcardCheckUtil;
import com.legrand.www.module.exception.exception.ExceptionBase;
import com.legrand.www.module.authentication.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


/**
 * @author xiah
 * @date 2018/4/26 16:24
 */
@Controller
@RequestMapping("/api/auth")
public class TokenController {

    private static final Logger logger = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/sec/test")
    @ResponseBody
    public BaseResponse test() {
        String name = UserUtil.getUserName();
        return new BaseResponse(name);

    }

    /**
     * @author xiah
     * description: 用户通过手机号和验证码获得token，refresh_token等信息
     * date: 2018/4/26
     */
    @RequestMapping(value = "/sec/getTokeByMobile", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse getTokeByMobile(@RequestParam String mobilePhone, @RequestParam String code) {
        if (!PhoneAndIDcardCheckUtil.isTelephone(mobilePhone)) {
            throw new ExceptionBase(122, "phoneNumber is wrong");
        }
        /*登陆成功将用户信息保存到UserUtil*/
        String name = UserUtil.getUserName();
        return new BaseResponse(name);
        //return new BaseResponse(JwtToken.creatTokenMap());
        //userService.getUser();
        //return "";
    }

    /**
     * @author xiah
     * description: 用户通过手机号和验证码获得token，refresh_token等信息
     * date: 2018/4/26
     */
    @RequestMapping(value = "/refreshToke")
    @ResponseBody
    public BaseResponse refreshToke(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getHeader("refresh_token");
        String refresh_token = request.getHeader("refresh_token");
        Optional<User> uu = Optional.of(new User());
        if (refresh_token == null) {
            throw new ExceptionBase(122, "phoneNumber is wrong");
        }
        if (!JwtToken.checkToken(TokenUtil.interceptToken(refresh_token))) {
            response.setStatus(500);
            throw new ExceptionBase(122, "phoneNumber is wrong");
        }
        return new BaseResponse(JwtToken.createToken());
        //userService.getUser();
        //return "";
    }

    /**
     * @author xiah
     * 2018-06-27 03:04:40
     * 用户使用账号密码登录
     */
    @PostMapping("/userName")
    public BaseResponse<TokenDTO> accessTokenByUsername(@RequestBody UserPTO pto) throws Exception {
        if (null == pto) {
            logger.error("Request body is null");
            throw new Exception("Request body is null");
        }
        final String userName = pto.getUserName();
        final String password = pto.getPassword();
        if (StringUtils.isBlank(userName)) {
            logger.error("Request body json username is null or empty");
            throw new Exception("Request body json username is null or empty");
        }
        if (StringUtils.isBlank(password)) {
            logger.error("Request body json password is null or empty");
            throw new Exception("Request body json password is null or empty");
        }
        TokenDTO token = userService.checkUser(userName, password);
        return new BaseResponse<>(token);
    }
}
